package com.breeze.components.task.lock;

import cn.hutool.core.util.StrUtil;
import java.util.Arrays;
import java.util.Objects;

/**
 * 调度类型
 *
 * @author breeze
 */
public enum ScheduleType {
  NONE(),
  CRON(),
  FIXED_RATE(),
  FIXED_DELAY();

  public static ScheduleType scheduleType(LockScheduled lockScheduled) {
    if (lockScheduled.fixedDelay() > 0 || StrUtil.isNotEmpty(lockScheduled.fixedDelayString())) {
      return ScheduleType.FIXED_DELAY;
    } else if (lockScheduled.fixedRate() > 0
        || StrUtil.isNotEmpty(lockScheduled.fixedRateString())) {
      return ScheduleType.FIXED_RATE;
    } else if (StrUtil.isNotEmpty(lockScheduled.cron())) {
      return ScheduleType.CRON;
    }
    return ScheduleType.NONE;
  }

  public static ScheduleType fromName(String scheduleType) {
    return Arrays.stream(values())
        .filter(s -> StrUtil.equals(s.name(), scheduleType))
        .findFirst()
        .orElse(null);
  }

  public String scheduleConf(LockScheduled lockScheduled) {
    return switch (this) {
      case CRON -> lockScheduled.cron();
      case FIXED_RATE ->
          Objects.equals(lockScheduled.fixedRate(), -1)
              ? lockScheduled.fixedRateString()
              : String.valueOf(lockScheduled.fixedRate());
      case FIXED_DELAY ->
          Objects.equals(lockScheduled.fixedDelay(), -1)
              ? lockScheduled.fixedDelayString()
              : String.valueOf(lockScheduled.fixedDelay());
      default -> StrUtil.EMPTY;
    };
  }
}
